package com.hmall.order.task;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.feign.client.ItemFeign;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
// @EnableAsync //异步功能
public class DelayTask {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    ItemFeign feign;
    @Scheduled(fixedRate = 1000*60) //每分钟查询一次数据库的订单
    @GlobalTransactional
    public void checkOrder(){
        //查询未支付的订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status" , 1);
        List<Order> list = orderService.list(queryWrapper);
        //遍历集合
        for (Order order : list) {
            //取出订单的创建时间
            long createTime = order.getCreateTime().getTime();
            //系统现在时间
            long nowTime = System.currentTimeMillis();
            //订单超时
            if (nowTime - createTime > 1000*60*30){
                //删除当前的订单
                System.out.println(order.getId()+"订单30分钟未支付,即将删除订单");
                //将订单状态改成5
                order.setStatus(5);
                orderService.updateById(order);
                //恢复库存
                Wrapper<OrderDetail> query = new QueryWrapper<>();
                ((QueryWrapper<OrderDetail>) query).eq("order_id" ,order.getId());
                OrderDetail detail = orderDetailService.getOne(query);
                //得到商品数量
                Integer num = detail.getNum();
                //得到商品id
                Long itemId = detail.getItemId();
                //远程调用更改商品库存
                feign.updateStock(itemId,num);
            }
        }
    }
}
